package com.heima.user.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojo.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.user.vo.LoginVo;
import com.heima.user.vo.UserVo;
import com.heima.utils.common.AppJwtUtil;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;

@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    /**
     * 登录接口
     *   二合一，用户登录也是有游客登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        //接受用户名和密码判断是否为空
        String phone = dto.getPhone();
        String password = dto.getPassword();
        //如果都为空则用0生成jwt返会
        if (StrUtil.isBlank(phone)||StrUtil.isBlank(password)){
            String token = AppJwtUtil.getToken(0l);
            LoginVo loginVo = new LoginVo();
            loginVo.setToken(token);
            return ResponseResult.okResult(loginVo);
        }

        //用户名和密码生成jwt令牌
        ApUser user = this.lambdaQuery().eq(ApUser::getPhone, phone).one();
        boolean isPasswordCorrect = BCrypt.checkpw(password, user.getPassword());
        if (user==null){
            return ResponseResult.okResult(1002,"用户不存在");
        }
        if (!isPasswordCorrect){
            return ResponseResult.okResult(2,"密码错误");
        }
        String token = AppJwtUtil.getToken(Long.valueOf(user.getId()));
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setUser(new UserVo());
        loginVo.getUser().setId(user.getId());
        loginVo.getUser().setName(user.getName());
        loginVo.getUser().setPhone(user.getPhone());
        return ResponseResult.okResult(loginVo);
    }

    /**
     * 根据用户id获取用户实体
     *
     * @param userId
     * @return
     */
    @Override
    public ResponseResult<ApUser>findUserById(Integer userId) {
        ApUser apUser = getById(userId);
        return ResponseResult.okResult(apUser);
    }
}
